#include "umSharePtr.h"
#include "um_basic_types.h"
#include "umapi_libc.h"
#include <signal.h>
#include "stdatomic.h"
//#include <atomic>

#define MAGIC 0x99558844
typedef struct
{
	int magic;
	int len;
	_Atomic int ref;
	onDestory freeCall;
	int data[0];
}S_PTR;
void * sharePtr_malloc(int s,  onDestory destoryCall)
{
	S_PTR *p = malloc(s + sizeof(S_PTR));
	memset(p, 0, s + sizeof(S_PTR));
	p->magic = MAGIC;
	p->len = s;
	p->ref = ATOMIC_VAR_INIT(1);
	p->freeCall = destoryCall;
	return p->data;
}
void sharePtr_ref(void *p)
{
	if(!p)
		return;
	S_PTR *s = p - sizeof(S_PTR);
	if(s->magic != MAGIC)
		return ;
	atomic_fetch_add(&s->ref,1);
}
void sharePtr_unref(void **p)
{
	if(!p || !*p)
		return;
	S_PTR *s = *p - sizeof(S_PTR);
	if(s->magic != MAGIC)
		return ;
	atomic_fetch_sub(&s->ref,1);
	if( s->ref == 0)
	{
		if(s->freeCall)
			(s->freeCall)(*p);
		*p = UM_NULL;
		free(s);
	}
}

